# 进行UDP链接类
import socket
import struct 
from src import trigger_multiip,trigger_multiport,dport

class udp_server(object):
    

    def __init__(self, my_ip, my_port):
        self.local_addr = (my_ip, my_port)
        self.socket = None

    def open(self):
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.socket.bind(self.local_addr)
        except socket.error as e:
            print(f"Socket error occurred: {e}")
            if hasattr(self, 'socket'):
                self.socket.close()
            raise  # 重新抛出异常以便上层处理

    def close(self):
        if self.socket:
            self.socket.close()

    def sent_message(self, buf, d_ip, d_port):
        try:
            self.socket.sendto(bytes(buf), (d_ip, d_port))
        except Exception as e:
            print(f"Error1: {e}")
            
    def receive_message(self):
        receive_data = self.socket.recvfrom(1024)
        receive_content = receive_data[0]
        # receive_localAddr = receive_data[1]
        recv_buf = ""
        recv_message = []
        for i in range(len(receive_content)):
            recv_message.append(receive_content[i])
            recv_buf = recv_buf + str(hex(receive_content[i])) + " "
        return recv_message
    


def join_multicast_group():
    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_address = ("0.0.0.0", trigger_multiport)
    # 绑定套接字到本地地址和端口
    sock.bind(server_address)

    # 将套接字绑定到组播地址和端口
    group = socket.inet_aton(trigger_multiip)
    mreq = struct.pack('4sL', group, socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    
    
    print(f"Listening on multi port {trigger_multiport}")
    return sock

def listen_unicast():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('0.0.0.0', dport))

    print(f"Listening on unicast port {dport}")
    return sock

